package web;
/*
用户添加功能：将页面表单中填写的内容保存到数据库中
 */
import com.fasterxml.jackson.databind.ObjectMapper;
import service.AddUserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class EnrollServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            System.out.println("EnrollServlet已经接收到客户端的请求。。。。。");
            //1.获取前台的参数username,password
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            //2.创建一个map对象，给map中设置内容
            Map<String, Object> map = new HashMap<>();
           //3.判断password长度是否符合规范
            if(password.length() < 28 && password.length() > 0){
                //4.调用service的AdduserService方法，返回boolean值
                boolean flag = new AddUserService().addUserService(username,password);
                if(flag) {
                    // 如果是true，则表示添加成功
                    map.put("isPass", true);
                    map.put("msg","已经成功添加");
                }
                else {
                    //如果false，则说明该用户名已经被注册过了
                    map.put("isPass",false);
                    map.put("msg","该用户名已被使用过，请换一个用户名添加");
                }
            }
            else{
                //说明长度超出规定
                map.put("isPass",false);
                map.put("msg","密码长度不符合范围，请重新输入");
            }
            //5 map转成json返回给前台
            ObjectMapper om = new ObjectMapper();
            String mapJson = om.writeValueAsString(map);
            //6 json数据返回给前台
            resp.getWriter().println(mapJson);
            System.out.println(mapJson);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
